package com.yc.encrypt.jwt;


import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class C1 {
	
	public String m1(String data, String key) {
		return JWT.create().withAudience(data).withIssuedAt(DateUtil.date()).sign(Algorithm.HMAC256(key));
	}
	
//	参考https://www.jb51.net/article/163069.htm
	
	private static final Algorithm ALGORITHM= Algorithm.HMAC256("security");
	
	//加密
	public String m1_en() {
		//通过秘钥生成一个算法
		String token = JWT.create()
		//设置签发者
		.withIssuer("test")
		//设置过期时间为一个小时
		.withExpiresAt(new Date(System.currentTimeMillis()+60*60*1000))
		//设置用户信息
		.withClaim("name","小明")
		.withClaim("age",20)
		.sign(ALGORITHM);
		return token;
	}
	
	//验证
	public void m1_ver(String token) {
		//校验类
		JWTVerifier JWT_VERIFIER= JWT.require(ALGORITHM).withIssuer("test").build();
		DecodedJWT decodedJWT = JWT_VERIFIER.verify(token);
	}
	
//	----------------------------------------------------------------------------
//	参考https://www.jianshu.com/p/99a458c62aa4
	
	public void m2() {
		JwtBuilder builder= Jwts.builder()
				 .setId("888")   //设置唯一编号
				 .setSubject("小白")//设置主题  可以是JSON数据
				 .setIssuedAt(new Date())//设置签发日期
				 .signWith(SignatureAlgorithm.HS256,"hahaha");//设置签名 使用HS256算法，并设置SecretKey(字符串)
				//构建 并返回一个字符串 
				System.out.println( builder.compact() );
	}
	
	public void m2_1() {
		 String compactJwt="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiLlsI_nmb0iLCJpYXQiOjE1NTc5MDQxODF9.ThecMfgYjtoys3JX7dpx3hu6pUm0piZ0tXXreFU_u3Y";
		 Claims claims = Jwts.parser().setSigningKey("hahaha").parseClaimsJws(compactJwt).getBody();
		 System.out.println(claims);
	}
	
	public void m2_2() {
		long now=System.currentTimeMillis();
		long exp=now+1000*30;//30秒过期
		JwtBuilder jwtBuilder = Jwts.builder().setId( "888" )
		 .setSubject( "小白" )
		 .setIssuedAt( new Date() )//签发时间
		 .setExpiration( new Date( exp ) )//过期时间
		 .claim( "roles","admin" )
		 .signWith( SignatureAlgorithm.HS256, "hahaha" );
		String token = jwtBuilder.compact();
		System.out.println(token);
	}
	
	public void m2_3() {
		String token ="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiLlsI_nmb0iLCJpYXQiOjE1NjIyNTM3NTQsImV4cCI6MTU2MjI1Mzc4Mywicm9sZXMiOiJhZG1pbiJ9.CY6CMembCi3mAkBHS3ivzB5w9uvtZim1HkizRu2gWaI";
		Claims claims = Jwts.parser().setSigningKey( "hahaha" ).parseClaimsJws( token ).getBody();
		System.out.println(claims);
		System.out.println(claims.get( "roles" ));
	}

	public static void main(String[] args) {
		C1 c = new C1();
//		System.out.println(c.m1("admin", "123"));
//		c.m2_1();
//		c.m2_2();
		c.m2_3();

	}

}
